package com.satan.fmmall.interceptor;

import com.alibaba.fastjson.JSON;
import com.satan.fmmall.entity.User;
import com.satan.fmmall.utils.JwtUitls;
import com.satan.fmmall.utils.UserThreadLocal;
import com.satan.fmmall.vo.ResCode;
import com.satan.fmmall.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName LoginInterceptor
 * @Description TODO
 * @date 2022/4/2 12:13
 * @Version 1.0
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器生效!");
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token=request.getHeader("Authorization");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}", requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (token == null) {
            doResponse(response, ResultVo.fail(ResCode.NO_LOGIN));
            log.info("拦截器未放行,token空值!");
            return false;
        }
        //验证token是否正确
        ResultVo resultVo = JwtUitls.checkToken(token);
        //验证正确
        if (resultVo.getCode()==200){
            Integer userId=JwtUitls.getUserId(token);
            //获取用户id并拿到用户信息
            String userJson = redisTemplate.opsForValue().get("TOKEN_USER_" + userId);

            if (StringUtils.isEmpty(userJson)) {
                doResponse(response, ResultVo.fail(ResCode.NO_LOGIN));
                System.out.println("拦截器未放行,userJson为空!");
                return false;
            }
            //String jsonObject = (String) JSON.parse(userJson);
            User user = JSON.parseObject(userJson, User.class);
            if (user == null) {
                doResponse(response, ResultVo.fail(ResCode.NO_LOGIN));
                log.info("拦截器未放行,user空值!");
                return false;
            }
            //是登录状态，放行
            log.info("user = {}", user);
            UserThreadLocal.put(user);
            System.out.println("拦截器放行!");
            return true;
        }else {
            doResponse(response, resultVo);
        }
        return false;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        System.out.println("UserThreadLocal被移除了");
    }

    private void doResponse(HttpServletResponse response,ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(resultVo));
        out.flush();
        out.close();
    }
}
